//
//  PlusMoreView.m
//  BaChat
//
//  Created by 刘洋 on 16/6/21.
//  Copyright © 2016年 刘洋. All rights reserved.
//

#import "PlusMoreView.h"
#import "PlusMoreCollectionViewCell.h"
#import "IflyTool.h"
#import "LocationViewController.h"
#import "shareLocationViewController.h"

@interface PlusMoreView ()<UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,retain)BaseCollectionView *moreCollectionView;
@property(nonatomic,retain)NSMutableArray *imageArray;
@property(nonatomic,retain)NSMutableArray *titleArray;


@end



@implementation PlusMoreView


-(void)dealloc{
    Block_release(_selectedImageBlock);
    Block_release(_localPathBlock);
    [_imageArray release];
    [_titleArray release];
    [_moreCollectionView release];
    [super dealloc];
    
}




-(instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    if (self) {
        [self createCollectionView];
      
    }
    return self;
    
    
}


-(void)createCollectionView{
    
    self.imageArray = [NSMutableArray arrayWithObjects:[UIImage imageNamed:@"message_more_pic"],[UIImage imageNamed:@"message_more_camera"],[UIImage imageNamed:@""],[UIImage imageNamed:@""],[UIImage imageNamed:@""], nil];
    
    
    self.imageArray = [NSMutableArray arrayWithObjects:
                       [UIImage imageNamed:@"message_more_pic"],
                       [UIImage imageNamed:@"message_white"],
                       [UIImage imageNamed:@"message_more_camera"],
                       [UIImage imageNamed:@"message_white"],
                       [UIImage imageNamed:@"message_more_poi"],
                       [UIImage imageNamed:@"message_white"],
                       [UIImage imageNamed:@"message_more_voice"],
                       [UIImage imageNamed:@"message_white"],nil];
    self.titleArray = [NSMutableArray arrayWithObjects:@"照片",@"",@"拍摄",@"",@"位置",@"",@"语音输入",@"",nil];


    // UICollectionViewFlowLayout用来定义collectionView的布局的类
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    //设置每个item的大小(这里的item相当于我们tableView中的cell)
    
    CGFloat itemWidth = (ROOTWIDTH - (5 * 30)) / 4 ;
    
    CGFloat itemHeight = itemWidth;
    
    flowLayout.itemSize = CGSizeMake(itemWidth , itemHeight + 20);
    
    //设置滑动方向(横滑)
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //如果没有设置行间距系统会默认最小为10像素
    //设置item之间的间距
    flowLayout.minimumInteritemSpacing = 5;
    //设置行间距
    flowLayout.minimumLineSpacing = 30;
    //设置collectView距离屏幕上,左,下,右的距离
    flowLayout.sectionInset = UIEdgeInsetsMake(20, 30, 20, 30);
    

    self.moreCollectionView = [[BaseCollectionView alloc]initWithFrame:CGRectMake(0, 0, ROOTWIDTH, ROOTHEIGHT / 3) collectionViewLayout:flowLayout];
    [flowLayout release];
    
    self.moreCollectionView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.moreCollectionView];
    [_moreCollectionView release];
    
    
    //item注册
    [self.moreCollectionView registerClass:[PlusMoreCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    
    self.moreCollectionView.delegate = self;
    self.moreCollectionView.dataSource = self;

    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.imageArray.count;

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    PlusMoreCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    item.bgImageView.image = [self.imageArray objectAtIndex:indexPath.row];
    item.titleLabel.text = [self.titleArray objectAtIndex:indexPath.row];
    
    return item;
    
    
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    


    switch (indexPath.row) {
        case 0:
            NSLog(@"这是照片");
            
            [self openSystemPhoto];
    
            
            break;
        case 1:
            

            
            break;
        case 2:
            NSLog(@"这是拍摄");
            
            [self openSystemCamera];
            
            
            break;
        case 3:
            

            
            break;
        case 4:
            
            NSLog(@"这是位置共享");
            
            [self jumpToMap];
            break;
        case 5:
          
            
            break;
        case 6:
            
            NSLog(@"这是语音输入");
            
            [self voiceToTextView];
            
            break;
        case 7:
            
        
            break;
    
    
        default:
            break;
    }
    

}



#pragma mark -- 找到cell的控制器
-(UIViewController *)viewController{
    
    for (UIView *next = [self superview]; next; next = [next superview]) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            
            return (UIViewController *)nextResponder;
        }
    }
    
    return nil;
    
  
}


#pragma mark -- 打开系统相册
-(void)openSystemPhoto{
 /*
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
    //设置选图时的框
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen; //全屏模式
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.delegate = self;
    //允许编辑
    imagePickerController.allowsEditing = NO;
 
    [[self viewController] presentViewController:imagePickerController animated:YES completion:NULL];
*/
    
    [self showImagePickerForSourceType:UIImagePickerControllerSourceTypePhotoLibrary andCameraCaptureMode:UIImagePickerControllerCameraCaptureModePhoto withAllowsEditing:NO];
    
 
}

#pragma mark -- 没选图片点取消时走的方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
        NSLog(@"没选图片");
    [[self viewController] dismissViewControllerAnimated:YES completion:NULL];
    

}





#pragma mark -- 取出本地图片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    NSLog(@"%@",mediaType);
    
    //public.image 图片类型
    //public.movie 视频类型
    
    if ([mediaType isEqualToString:@"public.image"]) {
      
        
        //存入原图
        UIImage *selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        NSLog(@"%@",selectedImage);
        
        //将选好都图片block回调
        self.selectedImageBlock(selectedImage);
        
       
        
        
    }else{
        
        NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL];//视频路径
    //    NSString *localPath = [url path];
        
    //    NSLog(@"%@",localPath);
        
  //      self.localPathBlock(url);
        
    //  CGFloat Mb = [[NSData dataWithContentsOfURL:url] length]/1024.00 /1024.00;
      //  NSLog(@"%.2f",Mb);
        
        
   //     NSURL *newUrl = [self compressedURL];
        
   //     NSLog(@"%@",newUrl);
        
        [self compressVideoWith:url];
      
        
    }
    
    
     [picker dismissViewControllerAnimated:YES completion:NULL];
    
    


/*
    //保存图片至本地,
    
    //    NSLog(@"%@",image);
    
    [self saveImage:image withName:@"userImage.png"];
    
    //取出沙盒图片
    NSString *filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"userImage.png"];
    
    UIImage *savedImage = [[UIImage alloc]initWithContentsOfFile:filePath];
    
    //重新添加图片
    [_userImage setImage:savedImage];
    
  */
}

/*
#pragma mark -- 保存图片方法
-(void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName{
    
    //    NSLog(@"%@",currentImage);
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 1);//1为不缩放保存,取消(0 - 1)
    
    //获取沙盒目录
    NSString *filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:imageName];
    
    //写入沙盒
    [imageData writeToFile:filePath atomically:NO];
    
    //    NSLog(@"%@",filePath);
    
}
*/

#pragma mark -- 打开系统相机
-(void)openSystemCamera{
    

    [self showImagePickerForSourceType:UIImagePickerControllerSourceTypeCamera andCameraCaptureMode:UIImagePickerControllerCameraCaptureModePhoto withAllowsEditing:NO];
    
    
}


#pragma mark -- 调用系统相机或相册的方法
-(void)showImagePickerForSourceType:(UIImagePickerControllerSourceType)sourceType andCameraCaptureMode:(UIImagePickerControllerCameraCaptureMode)mode withAllowsEditing:(BOOL)editing{
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
    //vc的各种model形式
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen; //全屏模式
    imagePickerController.sourceType = sourceType;
    
    imagePickerController.delegate = self;
    
    //是否允许拍照后编辑
    imagePickerController.allowsEditing = editing;
    
    //显示默认相机UI,默认为yes是显示
    //    imagePickerController.showsCameraControls = NO;
  
     if (sourceType == UIImagePickerControllerSourceTypeCamera) {
         
         //支持的设置类型,拍照或者摄影,此处将本设备支持的所有类型全部获取,并且同时赋值给imagePickerController的话,则可以左右切换摄制模式
    imagePickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//媒体类型为相机
         
         
     //设置模式--拍照/摄像
     imagePickerController.cameraCaptureMode = mode;
     //开启默认摄像头 -- 前置/后置
     imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
     //设置默认的闪光灯模式--开/关/自动
     imagePickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
     //拍摄时预览view的transform属性,可以实现旋转,缩放功能
     //        imagePickerController.cameraViewTransform = CGAffineTransformMakeRotation(M_PI);
     //        imagePickerController.cameraViewTransform = CGAffineTransformMakeScale(2.0,2.0);
 

    
     }
  
    
    [[self viewController] presentViewController:imagePickerController animated:YES completion:NULL];
    
    
}

#pragma mark 保存压缩
-(NSURL *)compressedURL
{
    //文件名以时间为名
    int x = arc4random() % 100000;
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSString *fileVideoName = [NSString stringWithFormat:@"%d%d",(int)time,x];
    NSLog(@"%@",fileVideoName);
    
    return [NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",fileVideoName]]];
}

- (CGFloat)fileSize:(NSURL *)path
{
    return [[NSData dataWithContentsOfURL:path] length]/1024.00 /1024.00;
}


//压缩视频
-(void)compressVideoWith:(NSURL *)url{
    NSLog(@"开始压缩,压缩前大小 %f MB",[self fileSize:url]);

    AVURLAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:nil];

        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPreset640x480];
    
        exportSession.outputURL = [self compressedURL];
    
      //  NSLog(@"%@",[self compressedURL]);
        
        //优化网络
        exportSession.shouldOptimizeForNetworkUse = true;
        //转换后的格式
        exportSession.outputFileType = AVFileTypeMPEG4;
        //异步导出
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            // 如果导出的状态为完成
            if ([exportSession status] == AVAssetExportSessionStatusCompleted) {
                NSLog(@"压缩完毕,压缩后大小 %f MB",[self fileSize:exportSession.outputURL]);
               
                NSLog(@"压缩后的路径 %@",exportSession.outputURL);
                NSString *fliePath = [exportSession.outputURL path];
                NSLog(@"%@",fliePath);
                self.localPathBlock(fliePath);
                
            }else{
                NSLog(@"当前压缩进度:%f",exportSession.progress);
            }
            
      
        }];

}

#pragma mark -- 语音输入
-(void)voiceToTextView{
    NSLog(@"这是语音输入的点击方法");
    
  [[IflyTool shareTool] startRecognizer:^(IFlySpeechError *error, NSString *result) {
      
      if (error) {
          return ;
      }
      
      self.voiceToTextViewBlock(result);
      
      NSLog(@"%@",result);
  }];
    
    
}

#pragma mark -- 地图定位跳转
-(void)jumpToMap{
    
    //中间部分的提示框,title和message给nil就可以
    UIAlertController *_alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [_alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }]];
    
    [_alertController addAction:[UIAlertAction actionWithTitle:@"发送位置" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self location];
    }]];
 //   [_alertController addAction:[UIAlertAction actionWithTitle:@"共享位置" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
 //       [self shareLocation];
 //   }]];
    

    
    [[self viewController] presentViewController:_alertController animated:YES completion:nil];
}

-(void)location{
    LocationViewController *loVC = [LocationViewController new];
    [ [self viewController].navigationController pushViewController:loVC animated:YES];
}

-(void)shareLocation{
    shareLocationViewController *ToVC = [shareLocationViewController new];
    [ [self viewController].navigationController pushViewController:ToVC animated:YES];
    
}


-(void)showNoTouch{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[self viewController].view animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.color = [UIColor whiteColor];
    hud.labelColor = [UIColor blackColor];
    hud.labelText = @"程序猿正在日夜开发中";
    hud.dimBackground = YES;
    [hud hide:YES afterDelay:1];

}


@end
